import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import store from './store'
Vue.use(Router)

const RT = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [{
    path: '/',
    name: 'home',
    component: Home
  },
  {
    path: '/category',
    name: 'Category',
    component: () => import('./views/Category.vue')
  },
  {
    path: '/categorylist/:id',
    name: 'CategoryList',
    component: () => import('./views/CategoryList.vue'),
    meta: {
      hideBar: true
    }
  },
  {
    path: '/goodsDetail/:gid',
    name: 'GoodsDetail',
    component: () => import('./views/GoodsDetail.vue'),
    meta: {
      hideBar: true
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('./views/Login.vue'),
    meta: {
      hideBar: true
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('./views/Register.vue'),
    meta: {
      hideBar: true
    }
  },
  {
    path: '/bookshop',
    name: 'Bookshop',
    component: () => import('./views/Bookshop.vue'),
    meta: {
      hideBar: true
    }
  },
  {
    path: '/cart',
    name: 'Cart',
    component: () => import('./views/Cart.vue'),
    meta: {
      hideBar: true
    }
  },
  {
    path: '/users',
    name: 'Users',
    component: () => import('./views/Users.vue'),
    meta: {
      hideBar: true
    }
  }

  ]
})

//  全局路由守卫,解决是否显示tabbar 的问题
RT.beforeEach((to, from, next) => {
  // 记录那些不需要登录的，通过localstorage来存储
  if (to.matched.some(current => current.meta.hideBar ? current.meta.hideBar : false)) {
    store.state.hideBar = false
  } else {
    store.state.hideBar = true
  }
  console.log(to.path)
  if (to.path === '/' || to.path === '/category' || to.path === '/login' || to.path === '/register' || to.path === '/category' || to.path.startsWith('/categorylist') || to.path.startsWith('/goodsDetail')) {
    next()
  } else {
    const token = localStorage.getItem('Authorization')
    console.log(token)
    if (token === null || token === '') {
      next('/login')
    } else {
      next()
    }
  }
})

// 导航守卫
// 使用router.beforeEach注册一个全局前置守卫,判断用户是否登录
/* router.beforeEach((to, from, next) => {
  console.log(to.path)
  if (to.path === '/search') {
    next()
  } else {
    const token = localStorage.getItem('Authorization')
    console.log(token)
    if (token === null || token === '') {
      next('/search')
    } else {
      next()
    }
  }
}) */

export default RT
